package pack1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Tabledesc  {

	Connection  con ;
	private	int rowcount ;
	private	int colcount ; 
	public int getColumnCount() {

		try{
			 con = DBconn.getConn();
			 Statement st = con.createStatement();
			 ResultSet rs = st.executeQuery("SELECT * from Inventory");
			 ResultSetMetaData rsmd = rs.getMetaData();
			 colcount = rsmd.getColumnCount();
		}catch(Exception e){
			System.out.println("Exception in Tabledesc.getColumnCount");
			e.printStackTrace();
		}
		return colcount;
	}

	public int getRowCount() {
		try{
			con = DBconn.getConn();
			Statement st = con.createStatement();
			String sql = "SELECT count(*) as cnt from Inventory " ;
			st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
			ResultSet rs = st.executeQuery(sql);
			
			 rowcount = rs.last() ? rs.getRow() : 0;
		}catch(Exception e){
			System.out.println("Exception in Tabledesc.getRowCount");
			e.printStackTrace();
		}
			return rowcount;
	}

	public Object getValueAt(int row, int col) {

		Object res = null;
		try{
		con = DBconn.getConn();
		Statement st = con.createStatement();
		String sql = "SELECT * from Inventory " ;
		st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
		ResultSet rs = st.executeQuery(sql);
		
		rs.absolute(row);
		rs.getRow();
		
		res = rs.getObject(col);
		
		}catch(Exception e){
			System.out.println("Exception in Tabledesc.getValueAt");
			e.printStackTrace();
		}
		
		return res;
	}
	
	public Object setValueAt(int row, int col, Object value) {

		try{
			
			String item_id = getValueAt( row+1, 1).toString();
			String column_name = null;
			if (col==1)
			column_name = "Item";
			else if (col==2)
				column_name = "Price";
			else 
				column_name= "none ";
			
		con = DBconn.getConn();
		Statement st = con.createStatement();
		String sql = "UPDATE Inventory set "+column_name+"='"+ (value.toString())+"' where ID ="+ item_id +";";
		st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
		System.out.println(sql);
		int resu  = st.executeUpdate(sql);
		System.out.println("updated no of lines "+ resu);
		}catch(Exception e){
			System.out.println("Exception in Tabledesc.setValueAt");
			e.printStackTrace();
		}
		return null;
	}

}
